<?php
/**
 * Connection Class makes use of mysql PDO driver to  fetch data from
 * the database
 *
 * @author federico.rubini
 */
class Connection {
    static $conn;
    private $pdo;

    /**
     * Constuctor instantiate the PDO
     */
    private function __construct(){
        $this->pdo = new PDO(DBDNS, DBUSER, DBPASS);
    }

    /*
     * Singleton for database connection
     */
    public static function getInstance(){
        if(self::$conn === null){
            self::$conn = new Connection();
        }
        return self::$conn;
    }

    /**
     * Create SQL insert statements from an associative array
     *
     * @param <array> $values
     * @param <array> $class
     * @return <object> PDO result statement
     */
    public function insert($values, $class){
        $table = $this->getTableName($class);
        $sql='INSERT INTO '.$table.' ('.implode(',',array_keys($values)).')
             VALUES (\''.implode("','",array_values($values)).'\')';
        $this->pdo->exec($sql);
        return $this->pdo->lastInsertId();
    }

    /**
     * Creates SQL Update statements form an associative array
     *
     * @param array $values
     * @param <string> $class
     * @param <string> $primaryKey
     * @return <object> PDO result statement
     */
    public function update($values, $class, $primaryKey){
        $table = $this->getTableName($class);
        $sql = "UPDATE $table SET ";
        $i = 0;
        foreach($values as $columnName => $value){
            $sql .= " $columnName = '$value' ";
            $sql .= ($i++ < count($values))? ", " : "";
        }
        $sql .= " WHERE $primaryKey = '{$values[$primaryKey]}' ";
        return $this->pdo->exec($sql);
    }

    /**
     *
     * @param <string> $class
     * @param <int> $id
     * @return <object>
     */
    public function getObject($class, $id){
        $table = $this->getTableName($class);
        $stmt = $this->pdo->prepare("SELECT * FROM $table WHERE id = '$id' ");
        $stmt->setFetchMode(PDO::FETCH_CLASS, $class);
        $stmt->execute();
        return $stmt->fetch();
    }

    /**
     * get the table name from the object name
     *
     * @param <string> $className
     * @return <string>
     */
    private function getTableName($className){
        $nameParts = explode("_", $className);
        $tableName = strtolower(end($nameParts));
        return $tableName;
    }
}
